package com.lyb.services.impl;

import com.lyb.Security.LoginUser;
import com.lyb.common.AjaxResult;
import com.lyb.common.JWTDemo;
import com.lyb.pojo.User;
import com.lyb.services.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
@Service
public class LoginServiceImpl implements LoginService {
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public AjaxResult Login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }
        //使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        redisTemplate.opsForValue().set("login:" + userId, loginUser);
        Map<String, Object> id = new HashMap<>();
        id.put("id", userId);
        String jwt = JWTDemo.generateJwtToken(id);
        Map<String, Object> token = new HashMap<>();
        token.put("token", jwt);
        token.put("loginUser",loginUser.getUsername());
        return AjaxResult.success(token);
    }
}
